<template>
  <div  v-loading="loadingAll">
    <el-row>
      <el-col :span="12" :offset='6'>
        <el-form  v-if='editing' :model="agency" :rules="rules" ref="agency" label-width="100px"
          style="padding-top:40px">
          <el-form-item label="机构名称">{{ agency.agencyName }}</el-form-item>
          <el-form-item label="所属地区">{{ agency.areaName }}</el-form-item>
          <el-form-item label="机构图标" prop="icon">
            <el-input v-model="agency.icon" type='text' style='display:none'></el-input>
            <el-upload
              ref="upload"
              :headers="headers"
              action="/tools/oss/upload"
              :on-success="uploadIconSuccess"
              :before-upload="onBeforeUpload"
              :limit="2"
              :show-file-list='false'
              :file-list="fileList"
              :auto-upload="true"
              :accept="'.jpg,.png'"
              >
              <el-form-item class="imgBox" v-if="agency.icon != ''">
                <img :src="agency.icon" :alt="agency.icon" style="width:50%" @error="errorIcon()" />
              </el-form-item>
              <el-button size="small" type="primary">上传图标</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="机构特色" prop="feature">
            <el-col :span="21">
              <el-input placeholder="请输入机构特色" maxlength="100" v-model="agency.feature" type="textarea" :autosize="{ minRows: 2, maxRows: 4}">
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="主页背景" prop='image'>
            <el-input v-model="agency.image" type='text' style='display:none'></el-input>
            <el-upload
              ref="upload"
              :headers="headers"
              action="/tools/oss/upload"
              :on-success="uploadImageSuccess"
              :before-upload="onBeforeUpload"
              :limit="2"
              :show-file-list='false'
              :file-list="fileList"
              :auto-upload="true"
              :accept="'.jpg,.png'"
              >
              <el-form-item class="imgBox" v-if="agency.image != ''">
                <img :src="agency.image" :alt="agency.image" @error="errorImage()"/>
              </el-form-item>
              <el-button size="small" type="primary">上传背景</el-button>
            </el-upload>
          </el-form-item>

          <el-form-item label="详细地址" prop='address'>
            <el-input v-model="agency.address" type='text'></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop='telephone'>
            <el-input v-model="agency.telephone" type='text'></el-input>
          </el-form-item>
          <el-form-item label="机构官网" prop='website'>
            <el-input v-model="agency.website" type='text'></el-input>
          </el-form-item>
          <el-form-item label="机构简介" prop="description">
            <Tinymce :height='30' :value='agency.description' ref="editor" v-model="agency.description"/>
          </el-form-item>
          <el-form-item>
            <el-button :disabled='preventSumit' type="success" @click="save">保存</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { getToken } from '@/utils/auth' // 验权
import { getInfo, update } from '@/api/agency'
import { validateNumber, validateURL } from '@/utils/validate'


export default {
  name: 'articleDetail',
  props:{
    commodityId:{
      type:Number,
      required:false
    }
  },
  components: { Tinymce },
  data() {
    const validateNum = (rule, value, callback) => {
      if (!validateNumber(value)) {
        callback(new Error('请输入正确的联系方式'))
      } else {
        callback()
      }
    }
    const validateUrl = (rule, value, callback) => {
      if (!validateURL(value)) {
        callback(new Error('请输入正确的链接地址'))
      } else {
        callback()
      }
    }
    return {
      agency:{
        icon:'',
        image:''
      },
      headers:{},
      stepsActive:1,
      gradeList:[],
      subjectList:[],
      topicList:[],
      fileList:[],
      isCreateCommodity:true,
      lessonData:[],//课程列表
      isPreviewCommodity:true,
      typeDialogVisible:false,
      editing:true,
      loadingAll:false,
      preventSumit:false,
      rules:{
        icon: [ { required: true, message: '请上传机构图标', trigger: 'change' } ],
        image: [ { required: true, message: '请上传主页背景', trigger: 'change' } ],
        address: [ { required: true, message: '请输入详细地址', trigger: 'blur' } ],
        feature: [ { required: true, message: '请输入机构特色', trigger: 'blur' } ],
        telephone: [ 
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        website: [ 
          { required: false, trigger: 'blur', validator: validateUrl }
        ],
        description: [ { required: true, message: '请输入机构简介', trigger: 'blur' } ]
      }
    }
  },
  created() { 
    this.headers = {accessToken:getToken()};
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    errorIcon(){
      this.agency.icon = '';
    },
    errorImage(){
      this.agency.image = '';
    },
    uploadIconSuccess(response, file, fileList){
      let { code , data:{picUrlList}, message } = response;
      if(code === '0'){
        this.fileList=[{name:picUrlList[0],url:picUrlList[0]}];
        this.$set(this.agency,'icon',picUrlList[0])
      }else{
        this.$refs.upload.clearFiles();
        this.$notify({
          title: '上传失败',
          message: message,
          type: 'error',
          duration: 3000
        });
      }
      this.preventSumit = false
    },
    uploadImageSuccess(response, file, fileList){
      let { code , data:{picUrlList}, message } = response;
      if(code === '0'){
        this.fileList=[{name:picUrlList[0],url:picUrlList[0]}];
        this.$set(this.agency,'image',picUrlList[0])
      }else{
        this.$refs.upload.clearFiles();
        this.$notify({
          title: '上传失败',
          message: message,
          type: 'error',
          duration: 3000
        });
      }
      this.preventSumit = false
    },
    fetchData() {
      this.listLoading = true
      getInfo().then(response => {
        this.agency = response.data
        this.listLoading = false
      })
    },
    save() {
      this.$refs.agency.validate(valid => {
        if (valid) {
          let params = this.agency;
          if(!params['description'].trim()){
            this.$notify({
              message: '请输入机构简介',
              type: 'error',
              duration: 1000
            });
            this.loading = false;
            return;
          }
          update(params).then(response => {
            const { code,message } = response
            if(code == 0){
              this.$message({message:'更新机构成功',type:'success',duration:1000})
            }else{
              this.$message(message)
            }
          });
        } else {
          this.$message({
            message:'请完善机构信息!',
            type:'warning'
          })
          return false
        }
      });
    },
    toEditCommodity () {
      this.editing = true
      this.stepsActive = 1
    },
    opreateCommodity (opreateFun) {
      this.agency.description = this.agency.description.trim()
      opreateFun(this.agency)
      .then(res => {
        const {code} = res
        const message = this.toBeEditedGoodId ? '修改成功!':'上架成功!'
        if(code === '0'){
          this.$message({
            message,
            type:'success'
          })
          this.$router.push('list')
          this.loadingAll = false
          if(this.toBeEditedGoodId) {
            this.$emit('edit-complete',true)
          }
        }
      })
      .catch(rej => {
        this.loadingAll = false
      })
    },
    createCommodity () {
      this.loadingAll = true
      const fun = this.toBeEditedGoodId ?  modifyGood : createGood;
      this.opreateCommodity(fun)
    },
    onBeforeUpload(file){
      this.preventSumit = true
    },
    chooseLesson (changeLesson,lessonData) {
      this.typeDialogVisible = false
      if(changeLesson){
        this.lessonData = []
        this.lessonData = this.lessonData.concat(lessonData)
        this.formatLessonIds()
      }
    },
    deleteLesson (index) {
      this.lessonData.splice(index,1)
      this.formatLessonIds()
    },
    deleteAllLesson () {
      this.$set(this,'lessonData',[])
      this.formatLessonIds()
    },
    getlessonListAll () {
      if(!this.toBeEditedGoodId){return ''}
      const params =  {
        tagOrTopic:'',
        pageNo: 1,
        pageSize: Infinity,
        startDate: '',
        endtDate: ''
      }
      getLessonsList(params).then(res => {
        const {code,data:{list}} = res
        if(code === '0'){
          Array.from(list,info =>{
            if(this.agency.lessonIds.includes(info.id)){
              this.lessonData.push(info)
            }
          })
        }
      })
    },
    getlessonList (ids) {
      if(!this.toBeEditedGoodId){return ''}
      ids.forEach((item)=>{
        getLessonDetail(item).then(res => {
          const {code,data} = res
          if(code === '0'){
            this.lessonData.push(data)
          }
        })
      })
      
    },
    formatLessonIds () {
      const lessonDataLength = this.lessonData.length
      const lessonData = this.lessonData
      this.agency.lessonIds = Array.from(lessonData,lesson=>lesson.id)
      // this.$set(this.agency,'lessonIds',Array.from(lessonData,lesson=>lesson.id))
    },
    
    gradeChange () {
      this.agency.subjectId = 0;
      // this.getSubjectsList(newGradeId)
    }
  },
  computed: {    
    getSubjectsList () {
      const gradeId = this.agency.gradeId
      this.gradeList.forEach(grade => {
        if(grade.id === gradeId){
          this.subjectList = grade.subjects
        }
      });
      return this.subjectList
    },
    
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.imgBox{
  width: 330px;
  height: 195px;
  overflow: hidden;
  img{
    width: 100%;
  }
}
.el-input-number{
  width:200px
}
.unlimtFormItem.uploadContainer{
  .el-upload__tip,
  .el-form-item__error{
    margin-left: 110px;
  }

}
</style>